package cn.jy.nvr.service.impl;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.jy.nvr.datasource.DataSourceConst;
import cn.jy.nvr.datasource.DataSourceContextHolder;
import cn.jy.nvr.domain.CommonDownFile;
import cn.jy.nvr.domain.DownloadItem;
import cn.jy.nvr.downfile.DownFile;
import cn.jy.nvr.mapper.CommonDownFileMapper;
import cn.jy.nvr.service.CommonDownFileQuartzJob;
@Service("quartzCommonDownFileJob")
public class CommonDownFileQuartJobImpl implements CommonDownFileQuartzJob {
	@Autowired
	CommonDownFileMapper commonDownFileMapper;
	public void work(){
		 DataSourceContextHolder.setDataSourceType(DataSourceConst.mx);
		List<CommonDownFile> all = commonDownFileMapper.getAll();
		for (CommonDownFile commonDownFile : all) {
			
			int year = 0;
			int month = 0;
		    int day = 0;
			int hour=0;
			int minute=0;	 
			int second=0;
			 try {
				Date date= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(commonDownFile.getSTART_TIME());
				Calendar filetime=Calendar.getInstance();
				filetime.setTime(date);
				 year=filetime.get(Calendar.YEAR);
				 month=(filetime.get(Calendar.MONTH) + 1);
				 day=filetime.get(Calendar.DAY_OF_MONTH);
				 hour=filetime.get(Calendar.HOUR_OF_DAY);
				 minute=filetime.get(Calendar.MINUTE);
				 second=filetime.get(Calendar.SECOND);
			} catch (ParseException e) {
				e.printStackTrace();
			}
			 String calendarPath=year+"/"+month+"/"+day+"/";
			 File file=new File("D:/apache-tomcat-7.0.79/webapps/Nvr/CommonVideo/"+calendarPath);
			 if(!file.exists()){
				 file.mkdirs();
			 }

			 String startTime=commonDownFile.getSTART_TIME();
			 String endTime=commonDownFile.getEND_TIME();
			 String channel=commonDownFile.getCHANNEL();
			 if((startTime!=null&&startTime.length()>0)&&(endTime!=null&&endTime.length()>0)&&(channel!=null&&channel.length()>0)){
				 DownloadItem downloadItem= new DownloadItem();
				 downloadItem.setChannel( new Integer( commonDownFile.getCHANNEL()));
				 downloadItem.setStart(commonDownFile.getSTART_TIME());
				 downloadItem.setEnd(commonDownFile.getEND_TIME());
				 downloadItem.setFilename(commonDownFile.getCHANNEL()+"-"+year+""+month+""+day+""+hour+""+minute+""+second);
				 downloadItem.setFilepath(file.getAbsolutePath()+"\\");
				 
				 File downFile= new File(downloadItem.getFilepath()+downloadItem.getFilename()+"jy.mp4");
				 if (downFile.exists()) {
					 downFile.delete();
				 }
				 DownFile.getInstance().downFileByTime(downloadItem);
				 
				 commonDownFile.setFILE_PATH("/CommonVideo/"+calendarPath+downloadItem.getFilename()+"jy.mp4");
				 System.out.println("写入下载路径到数据库");
				 DataSourceContextHolder.setDataSourceType(DataSourceConst.mx);
				 commonDownFileMapper.UpdateFilePathByID(commonDownFile);
			 }
		}
		
	}

}
